/**
 * SessionController
 *
 * @description :: Server-side logic for managing sessions
 * @help        :: See http://sailsjs.org/#!/documentation/concepts/Controllers
 */


var bcrypt= require('bcrypt-nodejs');

module.exports = {

	'new': function(req,res){
		res.view('session/new');
	},
	
	create: function(req,res,next){
		// if no data
		if (!req.param('username')||!req.param('password')) {
			var usernamePasswordRequiredError= [{name: 'usernamePasswordRequired', message:'Tienes que intoducir usuario y contraseña.'}]

			req.session.flash={
				err: usernamePasswordRequiredError
			}

			res.redirect('/session/new');
			return
		};


		// find the user
		User.findOneByUsername(req.param('username'), function foundUser(err,user){			
			if (err) return next(err);

			// if no user found
			if(!user){
				var noAccountError=[{name:'noAccount', message: 'El usuario ' + req.param('username') + ' no existe.'}]
				req.session.flash={
					err: noAccountError
				}
				res.redirect('/session/new');
				return;
			}


			// if found, compare the password			
			bcrypt.compare(req.param('password'),user.encryptedPassword, function(err,valid){
				if (err) return next(err);

				// if not match
				if(!valid){
					var usernamePasswordMismatchError = [{name: 'usernamePasswordMismatch', message: 'Contraseña erorena'}]
					req.session.flash={
						err: usernamePasswordMismatchError
					}
					res.redirect('/session/new');
					return;
				}

				// if GOOD login
				req.session.authenticated = true;
				req.session.User = user;

				if(req.session.User.admin){
					res.redirect('/user');
					return
				}
				// to show
				res.redirect('/user/show/' + user.id);
			});
		});
	},

	destroy: function(req,res,next){
		// delete the session
		req.session.destroy();

		// redirect to new
		res.redirect('/session/new');
	}

};